<?php

namespace Qdr\Jwt;

class Rsa2
{
    private $publicKey = '';
    private $privateKey = '';
    private $params = '';
    
    public function __construct()
    {
    }
    
    public function setPublicKey($key)
    {
        $this->publicKey = $key;
        return $this;
    }
    
    public function setPrivateKey($key)
    {
        $this->privateKey = $key;
        return $this;
    }
    
    public function setParams($params)
    {
        $this->params = json_encode($params);
        return $this;
    }
    
    /**
     * @return string|null
     * @throws Exception
     */
    public function setAuthorization(): string|null
    {
        $publicKey = openssl_pkey_get_public("-----BEGIN PUBLIC KEY-----\n" . $this->publicKey . "\n-----END PUBLIC KEY-----");
        $rs = openssl_public_encrypt(md5($this->params), $encrypted, $publicKey) ? base64_encode(time() . $encrypted) : null;
        if (!$rs) {
            throw new Exception('jwt token生成失败！~');
        }
        return $rs;
    }
    
    /**
     * @param $encrypted
     * @return string | null
     */
    public function getAuthorizationData($authorization): Array | null
    {
    
        $encrypted = base64_decode($authorization); // base64 解密
        $time = (int)substr($encrypted, 0, 10);
        $encrypted = substr($encrypted, 10);
        $key = openssl_pkey_get_private("-----BEGIN RSA PRIVATE KEY-----\n" . $this->privateKey . "\n-----END RSA PRIVATE KEY-----"); //解析私钥
        
        $dataMd5 = openssl_private_decrypt($encrypted, $decrypted, $key) ? $decrypted : null; // 获取到用户的MD5数据信息
        return [$time, $dataMd5];
    }
}